package net.gz01.wallet.web.model;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import net.gz01.util.ZODate;
import net.gz01.util.ZOMoney;
import net.gz01.util.ZONumberToCN;
import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.common.ZOSqlHelper;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.config.SystemEnum.BizType;
import net.gz01.wallet.web.config.SystemEnum.OrderStatus;
import net.gz01.wallet.web.controller.api.ylmodel.CasherDesk;
import net.gz01.wallet.web.model.base.BaseTradeOrder;
import net.gz01.wallet.web.service.CalcFeeService;

@SuppressWarnings("serial")
public class TradeOrder extends BaseTradeOrder<TradeOrder>{

	public static final TradeOrder dao = new TradeOrder().dao();

	public Page<TradeOrder> search(ZOSearchCondition sc) {
		int pageNumber = sc.page.getPageNum();
		int pageSize = sc.page.getNumPerPage();

		ZOSqlHelper sql = new ZOSqlHelper(" from trade_order");
		sql.equals("merchCode", sc.get("merchCode"));
		sql.equals("orderNo", sc.get("orderNo"));
		sql.equals("outOrderNo", sc.get("outOrderNo"));
		sql.equals("realName", sc.getStr("realName"));
		if (StrKit.notBlank(sc.getStr("bizType"))) {
			String bizType2 = sc.getStr("bizType2");
			if (StrKit.isBlank(bizType2)) {
				bizType2 = "";
			}
			String bizType3 = sc.getStr("bizType3");
			if (StrKit.isBlank(bizType3)) {
				bizType3 = "";
			}
			String bizType4 = sc.getStr("bizType4");
			if (StrKit.isBlank(bizType4)) {
				bizType4 = "";
			}
			String bizType5 = sc.getStr("bizType5");
			if (StrKit.isBlank(bizType5)) {
				bizType5 = "";
			}
			sql.in("bizType", sc.getStr("bizType"), bizType2, bizType3, bizType4, bizType5);
		}

		if (StrKit.notBlank(sc.getStr("orderStatus"))) {
			String orderStatus2 = sc.getStr("orderStatus2");
			if (StrKit.isBlank(orderStatus2)) {
				orderStatus2 = "";
			}

			String orderStatus3 = sc.getStr("orderStatus3");
			if (StrKit.isBlank(orderStatus3)) {
				orderStatus3 = "";
			}
			sql.in("orderStatus", sc.getStr("orderStatus"), orderStatus2, orderStatus3);
		}

		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		if(StrKit.notBlank(createTimeStart)){
			createTimeStart += " 00:00:00";
		}
		if(StrKit.notBlank(createTimeEnd)){
			createTimeEnd += " 23:59:59";
		}
		sql.date("createTime", createTimeStart, createTimeEnd);

		String price_min = sc.getStr("price_min");
		String price_max = sc.getStr("price_max");
		if(StrKit.notBlank(price_min)){
			price_min = ZOMoney.changeY2F(Double.parseDouble(price_min));
		}

		if(StrKit.notBlank(price_max)){
			price_max = ZOMoney.changeY2F(Double.parseDouble(price_max));
		}

		sql.date("amount", price_min, price_max);

		String realName = sc.getStr("realName");
		String mysql = "";
		if(StringUtils.isNotEmpty(sc.getStr("realName"))){
			mysql = "AND (accountName = '" + realName + "'" +
					"OR" + " payer='" + realName + "'" +
					"OR" + " realName='" + realName + "')";
		}

		sql.append(mysql + " ORDER BY CASE  WHEN orderStatus = 'R3' THEN 1 WHEN orderStatus = 'R2' THEN 2 WHEN orderStatus = 'R1' THEN 3 ELSE 4 END,createTime DESC ");
		return super.paginateByFullSql(pageNumber, pageSize, "select count(*) "+sql.toString(), "select * "+sql.toString(),sql.getParams());
	}



	public Page<TradeOrder> searchOrder(ZOSearchCondition sc) {
		int pageNumber = sc.page.getPageNum();
		int pageSize = sc.page.getNumPerPage();

		String feeInfo = sc.getStr("feeInfo");
		ZOSqlHelper sql = new ZOSqlHelper(" from trade_order");
		String myBizType = sc.getStr("bizTypex");
		sql.equals("merchCode", sc.get("merchCode"));
		sql.equals("orderNo", sc.get("orderNo"));
		sql.equals("outOrderNo", sc.get("outOrderNo"));
		sql.like("merchName", sc.get("merchName"));
		sql.like("realName", sc.get("myName"));
		String realName = sc.getStr("realName");
		String mysql = "";
		if(StringUtils.isNotEmpty(sc.getStr("realName"))){
			mysql = "AND (accountName = '" + realName + "'" +
					"OR" + " payer='" + realName + "'" +
					"OR" + " bankName='" + realName + "')";
		}

		if(myBizType!=null && myBizType.length() > 0) {
			String[] bizTypes = myBizType.split(";");
			Object[] bizObject = (Object[])bizTypes;
			sql.in("bizType", bizObject);
		}else {
			if (StrKit.notBlank(sc.getStr("bizType"))) {
				String bizType2 = sc.getStr("bizType2");
				if (StrKit.isBlank(bizType2)) {
					bizType2 = "";
				}
				String bizType3 = sc.getStr("bizType3");
				if (StrKit.isBlank(bizType3)) {
					bizType3 = "";
				}
				String bizType4 = sc.getStr("bizType4");
				if (StrKit.isBlank(bizType4)) {
					bizType4 = "";
				}
				String bizType5 = sc.getStr("bizType5");
				if (StrKit.isBlank(bizType5)) {
					bizType5 = "";
				}
				sql.in("bizType", sc.getStr("bizType"), bizType2, bizType3, bizType4, bizType5);
			}
		}

		if (StrKit.notBlank(sc.getStr("orderStatus"))) {
			String orderStatus2 = sc.getStr("orderStatus2");
			if (StrKit.isBlank(orderStatus2)) {
				orderStatus2 = "";
			}

			String orderStatus3 = sc.getStr("orderStatus3");
			if (StrKit.isBlank(orderStatus3)) {
				orderStatus3 = "";
			}

			String orderStatus4 = sc.getStr("orderStatus4");
			if (StrKit.isBlank(orderStatus4)) {
				orderStatus4 = "";
			}

			sql.in("orderStatus", sc.getStr("orderStatus"), orderStatus2, orderStatus3, orderStatus4);
		}

		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		if(StrKit.notBlank(createTimeStart)){
			createTimeStart += " 00:00:00";
		}
		if(StrKit.notBlank(createTimeEnd)){
			createTimeEnd += " 23:59:59";
		}
		sql.date("createTime", createTimeStart, createTimeEnd);

		String price_min = sc.getStr("price_min");
		String price_max = sc.getStr("price_max");
		if(StrKit.notBlank(price_min)){
			price_min = ZOMoney.changeY2F(Double.parseDouble(price_min));
		}

		if(StrKit.notBlank(price_max)){
			price_max = ZOMoney.changeY2F(Double.parseDouble(price_max));
		}
		if("1".equals(feeInfo)){
			mysql += " AND fee>0";
		}

		sql.date("amount", price_min, price_max);
		sql.append(mysql + " ORDER BY createTime DESC ");
		return super.paginateByFullSql(pageNumber, pageSize, "select count(*) "+sql.toString(), "select * "+sql.toString(),sql.getParams());
	}


	public List<TradeOrder> searchReportForAdminSheet(ZOSearchCondition sc){

		ZOSqlHelper sql = new ZOSqlHelper("select id, merchName, realName, merchCode,outOrderNo,accountNo,accountName, bankName, openingBankName, outBankName, outAccountNo,outAccountName, goodsNameUrl,createUser," +
				"goodsName,payer, buyer, orderNo,amount,fee,balance,orderStatus,bizType,createTime,payTime,respCode,respMsg,remark FROM trade_order");


		String feeInfo = sc.getStr("feeInfo");
		String myBizType = sc.getStr("bizTypex");
		sql.equals("merchCode", sc.get("merchCode"));
		sql.equals("orderNo", sc.get("orderNo"));
		sql.equals("outOrderNo", sc.get("outOrderNo"));
		String realName = sc.getStr("realName");
		String mysql = "";
		if(StringUtils.isNotEmpty(sc.getStr("realName"))){
			mysql = "AND (accountName = '" + realName + "'" +
					"OR" + " payer='" + realName + "'" +
					"OR" + " realName='" + realName + "')";
		}

		if(myBizType!=null && myBizType.length() > 0) {
			String[] bizTypes = myBizType.split(";");
			Object[] bizObject = (Object[])bizTypes;
			sql.in("bizType", bizObject);
		}else {
			if (StrKit.notBlank(sc.getStr("bizType"))) {
				String bizType2 = sc.getStr("bizType2");
				if (StrKit.isBlank(bizType2)) {
					bizType2 = "";
				}
				String bizType3 = sc.getStr("bizType3");
				if (StrKit.isBlank(bizType3)) {
					bizType3 = "";
				}
				String bizType4 = sc.getStr("bizType4");
				if (StrKit.isBlank(bizType4)) {
					bizType4 = "";
				}
				String bizType5 = sc.getStr("bizType5");
				if (StrKit.isBlank(bizType5)) {
					bizType5 = "";
				}
				sql.in("bizType", sc.getStr("bizType"), bizType2, bizType3, bizType4, bizType5);
			}
		}

		if (StrKit.notBlank(sc.getStr("orderStatus"))) {
			String orderStatus2 = sc.getStr("orderStatus2");
			if (StrKit.isBlank(orderStatus2)) {
				orderStatus2 = "";
			}

			String orderStatus3 = sc.getStr("orderStatus3");
			if (StrKit.isBlank(orderStatus3)) {
				orderStatus3 = "";
			}

			String orderStatus4 = sc.getStr("orderStatus4");
			if (StrKit.isBlank(orderStatus4)) {
				orderStatus4 = "";
			}

			sql.in("orderStatus", sc.getStr("orderStatus"), orderStatus2, orderStatus3, orderStatus4);
		}

		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		if(StrKit.notBlank(createTimeStart)){
			createTimeStart += " 00:00:00";
		}
		if(StrKit.notBlank(createTimeEnd)){
			createTimeEnd += " 23:59:59";
		}
		sql.date("createTime", createTimeStart, createTimeEnd);

		String price_min = sc.getStr("price_min");
		String price_max = sc.getStr("price_max");
		if(StrKit.notBlank(price_min)){
			price_min = ZOMoney.changeY2F(Double.parseDouble(price_min));
		}

		if(StrKit.notBlank(price_max)){
			price_max = ZOMoney.changeY2F(Double.parseDouble(price_max));
		}
		if("1".equals(feeInfo)){
			mysql += " AND fee>0";
		}

		sql.date("amount", price_min, price_max);
		sql.append(mysql + " ORDER BY createTime DESC ");

		return  find(sql.toString(), sql.getParams());
	}

	public Page<TradeOrder> searchOrderYouliAccount(ZOSearchCondition sc) {
		int pageNumber = sc.page.getPageNum();
		int pageSize = sc.page.getNumPerPage();
		ZOSqlHelper sql = new ZOSqlHelper(" from trade_order");

		String mysql = "";
		String youliaccount = sc.getStr("youliaccount");
		if(StringUtils.isNotEmpty(youliaccount)) {
			mysql = " AND (accountNo = '" +youliaccount + "'" +
					" OR outAccountNo= '" + youliaccount + "'" + ")";
		}

		sql.equals("merchCode", sc.get("merchCode"));
		sql.equals("orderNo", sc.get("orderNo"));
		sql.equals("outOrderNo", sc.get("outOrderNo"));
		if (StrKit.notBlank(sc.getStr("bizType"))) {
			String bizType2 = sc.getStr("bizType2");
			if (StrKit.isBlank(bizType2)) {
				bizType2 = "";
			}
			String bizType3 = sc.getStr("bizType3");
			if (StrKit.isBlank(bizType3)) {
				bizType3 = "";
			}
			String bizType4 = sc.getStr("bizType4");
			if (StrKit.isBlank(bizType4)) {
				bizType4 = "";
			}
			String bizType5 = sc.getStr("bizType5");
			if (StrKit.isBlank(bizType5)) {
				bizType5 = "";
			}
			sql.in("bizType", sc.getStr("bizType"), bizType2, bizType3, bizType4, bizType5);
		}

		if (StrKit.notBlank(sc.getStr("orderStatus"))) {
			String orderStatus2 = sc.getStr("orderStatus2");
			if (StrKit.isBlank(orderStatus2)) {
				orderStatus2 = "";
			}

			String orderStatus3 = sc.getStr("orderStatus3");
			if (StrKit.isBlank(orderStatus3)) {
				orderStatus3 = "";
			}

			String orderStatus4 = sc.getStr("orderStatus4");
			if (StrKit.isBlank(orderStatus4)) {
				orderStatus4 = "";
			}

			sql.in("orderStatus", sc.getStr("orderStatus"), orderStatus2, orderStatus3, orderStatus4);
		}

		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		if(StrKit.notBlank(createTimeStart)){
			createTimeStart += " 00:00:00";
		}
		if(StrKit.notBlank(createTimeEnd)){
			createTimeEnd += " 23:59:59";
		}
		sql.date("payTime", createTimeStart, createTimeEnd);
		sql.append(mysql + " ORDER BY payTime DESC ");
		return super.paginateByFullSql(pageNumber, pageSize, "select count(*) "+sql.toString(), "select * "+sql.toString(),sql.getParams());
	}


	/**
	 * 查询总交易金额，总手续费，总笔数
	 *
	 * @param sc
	 * @return
	 */
	public Record selectTotalInfo(ZOSearchCondition sc) {
		ZOSqlHelper sql = new ZOSqlHelper("SELECT SUM(amount) amount,SUM(fee) fee,COUNT(*) count FROM trade_order ");
		sql.equals("merchCode", sc.get("merchCode"));
		sql.equals("orderNo", sc.get("orderNo"));
		if (StrKit.notBlank(sc.getStr("bizType"))) {
			String bizType2 = sc.getStr("bizType2");
			if (StrKit.isBlank(bizType2)) {
				bizType2 = "";
			}
			String bizType3 = sc.getStr("bizType3");
			if (StrKit.isBlank(bizType3)) {
				bizType3 = "";
			}
			String bizType4 = sc.getStr("bizType4");
			if (StrKit.isBlank(bizType3)) {
				bizType4 = "";
			}
			String bizType5 = sc.getStr("bizType5");
			if (StrKit.isBlank(bizType3)) {
				bizType5 = "";
			}
			sql.in("bizType", sc.getStr("bizType"), bizType2, bizType3, bizType4, bizType5);
		}
		sql.equals("orderStatus", sc.get("orderStatus"));
		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		if(StrKit.notBlank(createTimeStart)){
			createTimeStart += " 00:00:00";
		}
		if(StrKit.notBlank(createTimeEnd)){
			createTimeEnd += " 23:59:59";
		}
		sql.date("createTime", createTimeStart, createTimeEnd);
		// 使用了聚合函数，同时没有group by则返回结果只有一行
		Record record = Db.findFirst(sql.toString(),sql.getParams());
		if (record.getLong("amount") == null) {
			record.set("amount", 0);
		}
		if (record.getLong("fee") == null) {
			record.set("fee", 0);
		}
		return record;
	}

	public Page<TradeOrder> searchForOrg(ZOSearchCondition sc,String orgCode){
		sc.put("orgCode", orgCode);
		return search(sc);
	}

	public Page<TradeOrder> searchForMerch(ZOSearchCondition sc,String merchCode){
		sc.put("merchCode", merchCode);
		return search(sc);
	}

	public TradeOrder selectByOrderNo(String orderNo) {
		return super.findFirst("select * from trade_order where orderNo = ?",orderNo);
	}

	public List<TradeOrder> searchReportForOrg(ZOSearchCondition sc, String orgCode){
		ZOSqlHelper sql = new ZOSqlHelper("select merchCode,merchOrderNo,orderNo,amount,merchFee,orderStatus,notifyStatus,bizType,createTime,payTime,respCode,respMsg FROM trade_order");
		sql.equals("orderStatus",sc.get("orderStatus"));
		sql.equals("merchOrderNo",sc.get("merchOrderNo"));
		sql.equals("merchCode",sc.get("merchCode"));
		sql.equals("orgCode",orgCode);
		sql.equals("orderNo",sc.get("orderNo"));
		sql.equals("bizType",sc.get("payType"));
		String payTimeStart = sc.getStr("payTimeStart");
		String payTimeEnd = sc.getStr("payTimeEnd");
		sql.date("payTime", payTimeStart, payTimeEnd);
		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		sql.date("createTime", createTimeStart, createTimeEnd);
		sql.orderBy("createTime","desc");
		return find(sql.toString(),sql.getParams());
	}

	public List<TradeOrder> searchTradeDetailReport(String beginDate,String endDate){
		ZOSqlHelper sql = new ZOSqlHelper("SELECT merchCode,orderNo,bizType,amount,fee,balance,payTime,accountNo,accountName FROM trade_order");
		sql.equals("orderStatus",OrderStatus.Success.getValue());
		sql.in("bizType","charge", "df_personal", "df_company");
		sql.date("settleDate", beginDate, endDate);
		sql.orderBy("bizType", "asc");
		sql.orderBy("payTime","desc");
		return super.find(sql.toString(),sql.getParams());
	}

	public List<TradeOrder> searchChargepayOrgReport(String orgCode,String beginDate,String endDate){
		ZOSqlHelper sql = new ZOSqlHelper("SELECT merchCode,orderNo,bizType,amount,fee,balance,payTime,accountNo,accountName FROM trade_order");
		sql.equals("orgCode",orgCode);
		sql.equals("orderStatus",OrderStatus.Success.getValue());
		sql.in("bizType","charge", "df_personal", "df_company");
		if(StrKit.notBlank(beginDate)){
			beginDate += " 00:00:00";
		}
		if(StrKit.notBlank(endDate)){
			endDate += " 23:59:59";
		}
		sql.date("createTime", beginDate, endDate);
		sql.orderBy("bizType", "asc");
		sql.orderBy("merchOrderNo","desc");
		return super.find(sql.toString(),sql.getParams());
	}

	public List<TradeOrder> searchChargepayMerchReport(String merchCode,String beginDate,String endDate){
		ZOSqlHelper sql = new ZOSqlHelper("SELECT merchCode,orderNo,bizType,amount,fee,balance,payTime,accountNo,accountName FROM trade_order");
		sql.equals("merchCode",merchCode);
		sql.equals("orderStatus",OrderStatus.Success.getValue());
		sql.in("bizType",BizType.DF_Company.getValue(), BizType.DF_Personal.getValue(), BizType.Charge.getValue());
		if(StrKit.notBlank(beginDate)){
			beginDate += " 00:00:00";
		}
		if(StrKit.notBlank(endDate)){
			endDate += " 23:59:59";
		}
		sql.date("createTime", beginDate, endDate);
		sql.orderBy("bizType", "asc");
		sql.orderBy("merchOrderNo","asc");
		return super.find(sql.toString(),sql.getParams());
	}

	public List<TradeOrder> selectClearingData(String settleDate){
		String sql = "SELECT id,channelCode,orgCode,merchCode,orderNo,bizType,amount,fee,payTime,settleDate FROM trade_order WHERE settleDate=? AND orderStatus IN (?)";
		return super.find(sql, settleDate, OrderStatus.Success.getValue());
	}

	//查询商户订单号是否存在
	public boolean isExitMerCodeNo(String merchCodeNo){
		if(selectMerCodeNo(merchCodeNo)!=null){
			return true;
		}
		return false;
	}

	public TradeOrder selectMerCodeNo(String merchCodeNo){
		return super.findFirst("select * from trade_order where outOrderNo = ?" ,
				merchCodeNo);
	}

	public TradeOrder selectMerCodeNo(String merchCodeNo, String bizType){
		return super.findFirst("select * from trade_order where outOrderNo = ? and bizType = ?" ,
				merchCodeNo, bizType);
	}

	public List<TradeOrder> searchReportForAdmin(ZOSearchCondition sc){
		ZOSqlHelper sql = new ZOSqlHelper("select id, merchName, merchCode,outOrderNo,accountNo,accountName, bankName, openingBankName, outBankName, outAccountNo,outAccountName, goodsNameUrl,createUser," +
				"goodsName,payer, buyer, orderNo,amount,fee,balance,orderStatus,bizType,createTime,payTime,respCode,respMsg,remark FROM trade_order");
		sql.equals("orderStatus",sc.get("orderStatus"));
		sql.equals("merchOrderNo",sc.get("merchOrderNo"));
		sql.equals("merchCode",sc.get("merchCode"));
		sql.equals("orgCode",sc.get("orgCode"));
		sql.equals("orderNo",sc.get("orderNo"));
		if (StrKit.notBlank(sc.getStr("bizType"))) {
			String bizType2 = sc.getStr("bizType2");
			if (StrKit.isBlank(bizType2)) {
				bizType2 = "";
			}
			sql.in("bizType", sc.getStr("bizType"), bizType2);
		}
		sql.equals("channelCode",sc.get("channelCode"));
		sql.equals("isInVirtualAccount",sc.get("isInVirtualAccount"));
		String payTimeStart = sc.getStr("payTimeStart");
		String payTimeEnd = sc.getStr("payTimeEnd");
		sql.date("payTime", payTimeStart, payTimeEnd);
		String createTimeStart = sc.getStr("createTimeStart");
		String createTimeEnd = sc.getStr("createTimeEnd");
		sql.date("createTime", createTimeStart, createTimeEnd);
		sql.orderBy("createTime","desc");

		return find(sql.toString(),sql.getParams());
	}

	public String getResp() {
		return getRespCode()+"-"+getRespMsg();
	}

	public String getAmountShow() {
		return getAmountFormat();
	}

	public String getAmountFormat() {
		String zf =  "";//"-";
//		if(getBizType().equals(BizType.TransferIn.getValue()) ||
//				getBizType().equals(BizType.ExpenseIn.getValue())||
//				getBizType().equals(BizType.Charge.getValue()) ||
//				getBizType().equals(BizType.Transfer_xx.getValue())){
//			zf = "+";
//		}
		return zf + "￥" + new DecimalFormat(",###,###,##0.00").format(getAmount()/100.0);
	}

	public String getAmountAbsShow(){
		return new DecimalFormat(",###,###,##0.00").format((Math.abs(getAmount()))/100.0);
	}

	public String getMerchFeeShow() {
		return getMerchFeeFormat();
	}

	public String getMerchFeeFormat() {
		if (getFee() == null) {
			return "￥0.00";
		}
		return "￥" + new DecimalFormat(",###,###,##0.00").format(getFee()/100.0);
	}

	public String getBalanceShow(){
		if(getBalance()==null){
			return "￥0.00";
		}
		return "￥" + new DecimalFormat(",###,###,##0.00").format(getBalance()/100.0);
	}

	public String getOrderStatusShow() {
		OrderStatus[] values = SystemEnum.OrderStatus.values();
		for (OrderStatus os : values) {
			if (Objects.equals(getOrderStatus(), os.getValue())) {
				return os.getName();
			}
		}
		return null;
	}

	public String getOrderStatusCustomerShow(){
		if(OrderStatus.Success.getValue().equals(getOrderStatus())){
			return "成功";
		}

		if(OrderStatus.Fail.getValue().equals(getOrderStatus())){
			return "失败";
		}

		if(OrderStatus.FirstReviewFail.getValue().equals(getOrderStatus())){
			return "失败1-原因:" + getPurpose();
		}

		if(OrderStatus.SecondReviewFail.getValue().equals(getOrderStatus())){
			return "失败2-原因:" + getPurpose2();
		}

		if(OrderStatus.ThirdReviewFail.getValue().equals(getOrderStatus())){
			return "失败3-原因:" + getPurpose3();
		}

		if(OrderStatus.WaitTransferFail.getValue().equals(getOrderStatus())){
			return "失败4-原因:" + getPurpose4();
		}

		return "处理中";
	}

	public String getBizTypeShow() {
		BizType[] values = BizType.values();
		for (BizType bizType : values) {
			if (Objects.equals(bizType.getValue(), getBizType())) {
				return bizType.getName();
			}
		}
		return null;
	}

	public String getAmountInWords() {
		return ZONumberToCN.number2CNMontrayUnit(ZOMoney.changeF2Y(getAmount()));
	}

	public TradeOrder select(String merchCode, String id) {
		return findFirst("select * from trade_order where merchCode = ? and id = ?", merchCode, id);
	}

	//创建支付支出订单---此订单是消费者的订单， 不收取手续费
	private CalcFeeService feeService = new CalcFeeService();
	public void createOrderPay(Merch merchBuyer, CasherDesk casherDesk, Merch merchSeller,
			TradeConfig config) {
		this.setId(ZOIDGenerate.getUUID());
		this.setChannelCode(config.getChannelCode());
		this.setOutOrderNo(casherDesk.getMallOrderNo());
		this.setOrderNo(ZOIDGenerate.getSixOrderNo());
		this.setBuyer(merchBuyer.getCode());

		this.setAccountNo(merchSeller.getCode());//钱包入账账号
		this.setAccountName(merchSeller.getName());//钱包入账商户名称

		this.setAmount(-Long.parseLong(casherDesk.getAmount()));
		this.setMerchName(merchBuyer.getName());
		this.setMerchCode(merchBuyer.getCode());
		this.setRealName(merchBuyer.getLegalPerson());

		MerchUser merchUser = MerchUser.dao.selectByMerCode(this.getMerchCode());
		this.setUserName(merchUser.getUserName());

		this.setCreateTime(ZODate.getDateTime());
		this.setGoodsName(casherDesk.getGoodNames());
		this.setReturnUrl(casherDesk.getReturnUrl());
		this.setOrderStatus(OrderStatus.InProcess.getValue());
		this.setPayer(casherDesk.getUserName());
		this.setOrgCode(SystemConfig.config.get("org_code"));
		this.setNotifyUrl(casherDesk.getNotifyUrl());
		this.setIsNotify(false);
//		Integer fee = feeService.getFee(this.getAmount().intValue(), config.getFeeId());
		this.setFee(0L);//(Long.parseLong(fee+""));//消费者没有手续费
		this.setBizType(BizType.ExpenseOut.getValue());
		this.save();
	}


	public void createChargeOrder(Merch merchBuyer, CasherDesk casherDesk, Merch merchSeller,
								  TradeConfig config, YouliAccount accountList){
		this.setId(ZOIDGenerate.getUUID());
		this.setChannelCode(config.getChannelCode());
		this.setOutOrderNo(casherDesk.getMallOrderNo());
		this.setOrderNo(ZOIDGenerate.getSixOrderNo());
		this.setBuyer(merchBuyer.getCode());

		this.setYouliAccountId(accountList.getId());
		this.setAccountNo(accountList.getAccountNo());//友利对公入账账号
		this.setAccountName(accountList.getAccountName());//友利对公银行名称
		this.setBankName(accountList.getBankName());
		this.setOpeningBankName(accountList.getOpeningBankName());
		this.setOpeningBankNo(accountList.getOpeningBankNo());

		this.setAmount(Long.parseLong(casherDesk.getAmount()));
		this.setMerchName(merchSeller.getName());
		this.setMerchCode(merchSeller.getCode());
		MerchUser merchUser = MerchUser.dao.selectByMerCode(this.getMerchCode());
		this.setUserName(merchUser.getUserName());
		this.setCreateTime(ZODate.getDateTime());
		this.setGoodsName(casherDesk.getGoodNames());
		this.setReturnUrl(casherDesk.getReturnUrl());
		this.setOrderStatus(OrderStatus.FirstReview.getValue());
		this.setPayer(casherDesk.getUserName()+ "-" + merchBuyer.getName());
		this.setPhoneNo(casherDesk.getUserName());
		this.setOrgCode(SystemConfig.config.get("org_code"));
		this.setNotifyUrl(casherDesk.getNotifyUrl());
		this.setIsNotify(false);
//		Integer fee = feeService.getFee(this.getAmount().intValue(), config.getFeeId());
		this.setFee(0L);//(Long.parseLong(fee+""));//消费者没有手续费
		this.setBizType(BizType.Charge.getValue());
		this.setRealName(merchSeller.getLegalPerson());//实名姓名或者公司名
		//this.setUserName(merchUser.getUserName());
		this.save();
	}

	public void createOrderPayIn(TradeOrder orderPay, String typeIn){
		boolean isNeedFee = false;
		if(SystemEnum.BizType.ExpenseIn.getValue().equals(typeIn)){
			isNeedFee = true; //钱包消费支付，手续费收取商家的。
		}

		this.setId(ZOIDGenerate.getUUID());
		this.setChannelCode(orderPay.getChannelCode());
		this.setOutOrderNo(orderPay.getOutOrderNo());
		this.setOrderNo(ZOIDGenerate.getSixOrderNo());
		this.setBuyer(orderPay.getBuyer());
		this.setAccountNo(orderPay.getMerchCode());
		this.setAccountName(orderPay.getMerchName());
		this.setOutAccountNo(orderPay.getMerchCode());
		this.setOutAccountName(orderPay.getMerchName());

		this.setAmount(Math.abs(orderPay.getAmount()));

		this.setMerchName(orderPay.getAccountName());
		this.setMerchCode(orderPay.getAccountNo());
		Merch merch = Merch.dao.selectByMerchCode(orderPay.getAccountNo());
		this.setRealName(merch.getLegalPerson());
		MerchUser merchUser = MerchUser.dao.selectByMerCode(merch.getCode());
		if(merchUser !=null) {
			this.setUserName(merchUser.getUserName());
		}
		this.setCreateTime(orderPay.getCreateTime());
		this.setGoodsName(orderPay.getGoodsName());
		this.setReturnUrl(orderPay.getReturnUrl());
		this.setOrderStatus(OrderStatus.Success.getValue());
		this.setPayer(orderPay.getPayer());
		this.setOrgCode(SystemConfig.config.get("org_code"));
		this.setNotifyUrl(orderPay.getNotifyUrl());
		this.setIsNotify(false);
		Integer fee = 0;
		if(isNeedFee) {
			TradeConfig tradeConfig = TradeConfig.dao.select(this.getMerchCode(),
					typeIn);
			if (tradeConfig == null) {
				fee = 0;
			} else {
				fee = feeService.getFee(this.getAmount().intValue(), tradeConfig.getFeeId());
			}
		}
		this.setFee(Long.parseLong(fee+""));
		this.setBalance(orderPay.getAccountBalance());
		this.setBizType(typeIn);

		this.setPayTime(orderPay.getPayTime());
		this.setSettleDate(ZODate.getDate());
		this.setOrderStatus(SystemEnum.OrderStatus.Success.getValue());
		this.setRespMsg(orderPay.getRespMsg());
		this.setRespCode(orderPay.getRespCode());
		this.setSettleDate(orderPay.getSettleDate());
		this.setPurpose(orderPay.getPurpose());
		this.save();
	}

	public List<TradeOrder> selectNewestTop(String merchCode, String date, int top) {
		return find("select * from trade_order where merchCode = ? and createTime like ? order by createTime desc limit ?", merchCode, date+"%", top);
	}


	public void updateNotifyStatus(String orderNo, boolean notifyStatus) {
		Db.update("update trade_order set isNotify = ? where outOrderNo = ?", notifyStatus,orderNo);
	}


	//付款类交易需要获取正整数来比较
	public Long getMathAbsAmt(){
		return Math.abs(getAmount());
	}

	public String getAccountNameShow(){
		if(getBizType()==null){
			return "未知";
		}

		if(getBizType().equals(BizType.ExpenseIn.getValue()) ||
				getBizType().equals(BizType.TransferIn.getValue())){
				return "打款账户:";
		}

		if(getBizType().equals(BizType.ExpenseOut.getValue()) ||
				getBizType().equals(BizType.TransferOut.getValue())){
			return "收款账户:";
		}

		return "账户:";
	}

	public String getAccountNoShow(){
		if(getBizType()==null){
			return "未知";
		}
		if(getBizType().equals(BizType.ExpenseIn.getValue()) ||
				getBizType().equals(BizType.TransferIn.getValue())){
			return "打款账号:";
		}

		if(getBizType().equals(BizType.ExpenseOut.getValue()) ||
				getBizType().equals(BizType.TransferOut.getValue())){
			return "收款账号:";
		}

		return "收款账号:";
	}

	public  boolean getIsExpense(){
		if(getBizType()==null){
			return false;
		}

		if(getBizType().equals(BizType.ExpenseOut.getValue()) ||
				getBizType().equals(BizType.ExpenseIn.getValue())){
			return true;
		}

		return false;
	}

	//获取是否老铁牛的线下转账的 订单
	public boolean getIsTransfer_xx(){

		if(getBizType()==null){
			return false;
		}

		if(getBizType().equals(BizType.Transfer_xx.getValue())){
			return true;
		}
		return false;
	}


	public boolean getIsAllShow(){
		return false;
	}

	//获取交易对手信息
	public String getTransInfo(){
		if(BizType.Charge.getValue().equals(getBizType())){
			return getPayer();
		}else {
			return getAccountName() + "-" + getAccountNo();
		}
	}


	/**
	 * 商户当前总交易金额
	 *
	 * @param merchCode
	 * @param settleDate
	 * @return
	 */
	public Long sumOrderAmount(String merchCode, String settleDate) {
		String sql = "select sum(amount) from trade_order where merchCode = ? and settleDate = ? and orderStatus = ?";
		BigDecimal sumAmount = Db.queryBigDecimal(sql, merchCode, settleDate, OrderStatus.Success.getValue());
		if(sumAmount == null) {
			sumAmount = BigDecimal.ZERO;
		}
		return sumAmount.longValue();
	}


	/**
	 * 商户当前支付类别总交易金额
	 *
	 * @param merchCode
	 * @param payType
	 * @param settleDate
	 * @return
	 */
	public Long sumPayTypeAmount(String merchCode, String payType, String settleDate) {
		String sql = "select SUM(amount) from trade_order where merchCode = ? and bizType = ? and settleDate = ? and orderStatus = ?";
		BigDecimal sumAmount = Db.queryBigDecimal(sql, merchCode, payType, settleDate, OrderStatus.Success.getValue());
		if(sumAmount == null) {
			sumAmount = BigDecimal.ZERO;
		}
		return sumAmount.longValue();
	}

	/**
	 * 商户当前总交易金额
	 *
	 * @param merchCode
	 * @return
	 */
	public Long sumAmount(String merchCode) {
		String sql = "SELECT SUM(amount) FROM trade_order WHERE merchCode = ? AND orderStatus = ?";
		BigDecimal sumAmount = Db.queryBigDecimal(sql, merchCode, OrderStatus.Success.getValue());
		if(sumAmount == null) {
			sumAmount = BigDecimal.ZERO;
		}
		return sumAmount.longValue();
	}


}
